#!/usr/bin/env python3
from redis.sentinel import Sentinel

class PySenConn:
    
    def __init__(self,nodes,service,password='',db=0):
        self.nodes=nodes
        self.service=service
        self.password=password
        self.db=db

        try:
            self.sentinel = Sentinel(self.nodes,socket_timeout=0.5,decode_responses=True)
            self.m = self.sentinel.discover_master(self.service)
            self.s = self.sentinel.discover_slaves(self.service)
            
            
            self.master = self.sentinel.master_for(
                service_name=self.service,
                password=self.password,
                db=self.db
            )
            self.slave = self.sentinel.slave_for(
                service_name=self.service,
                password=self.password,
                db=self.db
            )
        except Exception as e:
            print(e)
            print('Connect Failed...')

if __name__ == '__main__':
    #sens = [
    #    ('192.168.4.51',26379),
    #    ('192.168.4.52',26379),
    #    ('192.168.4.53',26379)
    #]
    sens = [ ('192.168.88.69',26379), ]
    service = "mymaster"
    #password = "123456"
    psc = PySenConn(sens,service)
    
    print("当前的主服务器是:%s" % psc.m[0])
    for slave in psc.s:
        print("当前的从服务器是:%s" % slave[0])

    psc.master.setex('a',5,'aaaaaaaaaaaaa')
    res = psc.slave.get('a')
    print('测试存储变量%s的值是%s' % ('a',res))
